﻿

 
using System;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using UserBook.Data;
using System.ComponentModel.Composition;

namespace UserBook.Repository
{

	[Export(typeof(IUnitOfWork))]
	public partial class UnitOfWork : IUnitOfWork
	{
		private readonly UserBookEntities _context;

		private readonly Lazy<IRepository<Contacto>> _contactoRepository;
		private readonly Lazy<IRepository<Empresa>> _empresaRepository;
		private readonly Lazy<IRepository<Rol>> _rolRepository;
		private readonly Lazy<IRepository<Usuario>> _usuarioRepository;
		private readonly Lazy<IRepository<UsuarioRol>> _usuarioRolRepository;

        public virtual IRepository<Contacto> ContactoRepository
        {
            get { return _contactoRepository.Value; }
        }

        public virtual IRepository<Empresa> EmpresaRepository
        {
            get { return _empresaRepository.Value; }
        }

        public virtual IRepository<Rol> RolRepository
        {
            get { return _rolRepository.Value; }
        }

        public virtual IRepository<Usuario> UsuarioRepository
        {
            get { return _usuarioRepository.Value; }
        }

        public virtual IRepository<UsuarioRol> UsuarioRolRepository
        {
            get { return _usuarioRolRepository.Value; }
        }

        public UnitOfWork() : this(new UserBookEntities())
        {
		}

        public UnitOfWork(UserBookEntities context)
        {
            _context = context;
			_context.ContextOptions.LazyLoadingEnabled = false;

            _contactoRepository = GetLazyRepository<Contacto>(_context);
            _empresaRepository = GetLazyRepository<Empresa>(_context);
            _rolRepository = GetLazyRepository<Rol>(_context);
            _usuarioRepository = GetLazyRepository<Usuario>(_context);
            _usuarioRolRepository = GetLazyRepository<UsuarioRol>(_context);
        }

        private static Lazy<IRepository<TEntity>> GetLazyRepository<TEntity>(ObjectContext context) where TEntity : EntityObject
        {
            return new Lazy<IRepository<TEntity>>(() => new EntityRepository<TEntity>(context));
        }

        public virtual bool Save()
        {
            return _context.SaveChanges() > 0;
        }

        #region IDisposable Methods

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion
	}
}


